package com.yjck.fm.spend.dao.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import com.yjck.fm.common.QueryResult;
import com.yjck.fm.spend.bean.SpendType;
import com.yjck.fm.spend.dao.SpendTypeDAO;
import com.yjck.fm.spend.dao.handler.SpendTypeRowMapper;

public class SpendTypeDAOImpl implements SpendTypeDAO {
	private JdbcTemplate jdbcTemplate;

	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
	/**
	 * 查询消费类型
	 */
	
	@SuppressWarnings("unchecked")
	public QueryResult getTypes(String typeName,int start, int limit) {
		String querySQL = "SELECT s.id,s.spendname,u.uname,s.createdate FROM spendtype s,user u WHERE s.createdby = u.id and s.spendname LIKE ? limit ? offset ?";
		String countSQL = "select count(id) from spendtype where spendname LIKE ?";
		Object[] params = new Object[]{'%'+typeName+'%',start+limit,start};
		List<SpendType> spendTypes = this.jdbcTemplate.query(querySQL,params,new SpendTypeRowMapper());
		int count = this.jdbcTemplate.queryForInt(countSQL, new Object[]{'%'+typeName+'%'});
		return new QueryResult(count, spendTypes);
	}
	
	
	
	/**
	 * 增加消费类型
	 */
	public boolean addType(String typeName,int id) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = sdf.format(new Date());
		String sql = "insert into spendtype(spendname,createdby,createdate,updatedby,updatedate) values(?,?,?,?,?)";
		Object[] params = new Object[]{typeName,id,date,id,date};
		int flag = this.jdbcTemplate.update(sql, params);
		if(flag > 0){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 删除消费类型
	 */
	public boolean delType(String sid) {
		String[] idArray = sid.split(",");
		String sql = "delete from spendtype where id = ?";
		boolean flag = false;
		for(String id : idArray){
			Object[] params = new Object[]{id};
			if(this.jdbcTemplate.update(sql, params)==1){
				flag = true;
			}else{
				flag = false;
				break;
			}
		}
		return flag;
	
	}
	/**
	 * 修改消费类型
	 */
	public boolean modifyType(String typeName, String sid, int updateby) {
		String sql = "update spendtype set spendname = ?,updatedby = ?,updatedate =? where id = ?";
		Object[] params = new Object[]{typeName,updateby,new SimpleDateFormat("yyyy-MM-dd").format(new Date()),sid};
		int num =this.jdbcTemplate.update(sql, params);
		if(num == 1){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 验证类型名称是否存在
	 */
	public boolean isExist(String typeName) {
		String sql = "select count(spendname) from spendtype where spendname = ?";
		Object[] params = new Object[]{typeName};
		if(this.jdbcTemplate.queryForInt(sql, params) > 0){
			return true;
		}else{
			return false;
		}
	}

}
